package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.dto.ConstructionWarningConfigDTO;
import com.ruoyi.system.entity.ConstructionWarningConfigDO;
import com.ruoyi.system.mapper.ConstructionWarningConfigMapper;
import com.ruoyi.system.service.IConstructionWarningConfigService;
import com.ruoyi.system.vo.ConstructionWarningConfigVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 施工预警配置服务实现类
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@Service
@Slf4j
public class ConstructionWarningConfigServiceImpl implements IConstructionWarningConfigService {

    @Resource
    private ConstructionWarningConfigMapper configMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean createConfig(ConstructionWarningConfigDTO configDTO) {
        try {
            ConstructionWarningConfigDO config = new ConstructionWarningConfigDO();
            BeanUtils.copyProperties(configDTO, config);
            
            // 转换触发条件为JSON字符串
            if (configDTO.getTriggerCondition() != null) {
                config.setTriggerCondition(objectMapper.writeValueAsString(configDTO.getTriggerCondition()));
            }
            
            // 设置默认值
            if (config.getIsEnabled() == null) {
                config.setIsEnabled(true);
            }
            
            config.setCreateTime(LocalDateTime.now());
            config.setUpdateTime(LocalDateTime.now());
            config.setIsDeleted(0);
            
            return configMapper.insert(config) > 0;
        } catch (Exception e) {
            log.error("创建预警配置失败: {}", e.getMessage(), e);
            throw new ServiceException("创建预警配置失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateConfig(ConstructionWarningConfigDTO configDTO) {
        try {
            ConstructionWarningConfigDO config = configMapper.selectById(configDTO.getId());
            if (config == null || config.getIsDeleted() == 1) {
                throw new ServiceException("预警配置不存在");
            }
            
            BeanUtils.copyProperties(configDTO, config);
            
            // 转换触发条件为JSON字符串
            if (configDTO.getTriggerCondition() != null) {
                config.setTriggerCondition(objectMapper.writeValueAsString(configDTO.getTriggerCondition()));
            }
            
            config.setUpdateTime(LocalDateTime.now());
            
            return configMapper.updateById(config) > 0;
        } catch (Exception e) {
            log.error("更新预警配置失败: {}", e.getMessage(), e);
            throw new ServiceException("更新预警配置失败: " + e.getMessage());
        }
    }

    @Override
    public boolean deleteConfig(Long configId) {
        try {
            ConstructionWarningConfigDO config = configMapper.selectById(configId);
            if (config == null || config.getIsDeleted() == 1) {
                throw new ServiceException("预警配置不存在");
            }
            
            config.setIsDeleted(1);
            config.setUpdateTime(LocalDateTime.now());
            
            return configMapper.updateById(config) > 0;
        } catch (Exception e) {
            log.error("删除预警配置失败: {}", e.getMessage(), e);
            throw new ServiceException("删除预警配置失败: " + e.getMessage());
        }
    }

    @Override
    public ConstructionWarningConfigVO getConfigDetail(Long configId) {
        ConstructionWarningConfigDO config = configMapper.selectById(configId);
        if (config == null || config.getIsDeleted() == 1) {
            throw new ServiceException("预警配置不存在");
        }
        
        return convertToVO(config);
    }

    @Override
    public List<ConstructionWarningConfigVO> getConfigList(String warningType) {
        LambdaQueryWrapper<ConstructionWarningConfigDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ConstructionWarningConfigDO::getIsDeleted, 0);
        
        if (StringUtils.isNotEmpty(warningType)) {
            queryWrapper.eq(ConstructionWarningConfigDO::getWarningType, warningType);
        }
        
        queryWrapper.orderByAsc(ConstructionWarningConfigDO::getWarningType)
                   .orderByAsc(ConstructionWarningConfigDO::getWarningLevel);
        
        List<ConstructionWarningConfigDO> configs = configMapper.selectList(queryWrapper);
        return configs.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public boolean toggleConfigStatus(Long configId, Boolean isEnabled) {
        try {
            ConstructionWarningConfigDO config = configMapper.selectById(configId);
            if (config == null || config.getIsDeleted() == 1) {
                throw new ServiceException("预警配置不存在");
            }
            
            config.setIsEnabled(isEnabled);
            config.setUpdateTime(LocalDateTime.now());
            
            return configMapper.updateById(config) > 0;
        } catch (Exception e) {
            log.error("切换预警配置状态失败: {}", e.getMessage(), e);
            throw new ServiceException("切换预警配置状态失败: " + e.getMessage());
        }
    }

    /**
     * 转换为VO
     */
    private ConstructionWarningConfigVO convertToVO(ConstructionWarningConfigDO config) {
        ConstructionWarningConfigVO vo = new ConstructionWarningConfigVO();
        BeanUtils.copyProperties(config, vo);
        
        // 设置类型名称
        vo.setWarningTypeName(getWarningTypeName(config.getWarningType()));
        vo.setWarningLevelName(getWarningLevelName(config.getWarningLevel()));
        
        // 解析触发条件
        if (StringUtils.isNotEmpty(config.getTriggerCondition())) {
            try {
                vo.setTriggerCondition(objectMapper.readValue(config.getTriggerCondition(), Map.class));
            } catch (Exception e) {
                log.warn("解析触发条件失败: {}", config.getTriggerCondition(), e);
                vo.setTriggerCondition(null);
            }
        }
        
        return vo;
    }

    /**
     * 获取预警类型名称
     */
    private String getWarningTypeName(String warningType) {
        switch (warningType) {
            case "progress":
                return "进度预警";
            case "quality":
                return "质量预警";
            default:
                return warningType;
        }
    }

    /**
     * 获取预警等级名称
     */
    private String getWarningLevelName(String warningLevel) {
        switch (warningLevel) {
            case "high":
                return "高危";
            case "medium":
                return "中危";
            case "low":
                return "低危";
            default:
                return warningLevel;
        }
    }
}

